/*	  Upload.js
 * *******************
 * A pretty generic FTP uploading library.
 * Used here for Images and any other file (only difference is File Picker filters and strings).
 *
 * Many thanks to Nickolay Ponomarev for his help.
 */
 
var gPffTempUploadObject = [];
var currentImagePath = "";

var gOpener = null;

if (window.opener.gPerformancingUtil) {
	var oPerformancingUtil = window.opener.gPerformancingUtil;
	gOpener = window.opener;
}
else if (window.opener.wrappedJSObject.gPerformancingUtil) {
	var oPerformancingUtil = window.opener.wrappedJSObject.gPerformancingUtil;
	gOpener = window.opener.wrappedJSObject;
}

var gPFF_MAGIC_NUMBER = 0x804b0000;
var gPFFNetErrorStrings = {
   "1": "Unexpected Error",                    //unexpected
   "2": "User Canceled Upload",                //usercancel
  "13": "FTP Refused Upload",                  //refused
  "14": "Network Timeout",                     //netTimeout
  "16": "Network Appears Offline",             //netOffline
  "21": "Incorrect User or Password",          //ftplogin
  "22": "ftpcwd",                              //ftpcwd
  "23": "ftppasv",                             //ftppasv
  "24": "Incorrect Password",                  //ftppwd
  "25": "ftplist",                             //ftplist
  "30": "Unknown Error"                        //unknown
};
var gPFFCI = Components.interfaces;
var gPFFCC = Components.classes;
var gPFFChannel = null;
var gTheErrorTimer = null;

var gTempObject = [];

var gUploadService = new Object();

gUploadService = {
    serviceType: null,
    //this.CR = Components.results;
    
	get prefs() { return oPerformancingUtil.prefs; },

    // uploads stream (nsIInputStream) to the specified location (nsIURI)
    upload: function(stream, uri) {
      var iosvc = gPFFCC["@mozilla.org/network/io-service;1"].getService(gPFFCI.nsIIOService);
      gPFFChannel = iosvc.newChannelFromURI(uri).QueryInterface(gPFFCI.nsIUploadChannel);
      gPFFChannel.setUploadStream(stream, "", -1);
      gPFFChannel.asyncOpen(gPFFStreamListener, window);
    },
    
    // returns an nsIInputStream suitable for passing to nsIUploadChannel.setUploadStream
    // aFile is the nsILocalFile, whose contents should be uploaded
    getUploadStreamForFile: function(aFile) {
      var fstream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream);
      fstream.init(aFile, 1, 0, 0);
    
      var bufStream = gPFFCC["@mozilla.org/network/buffered-input-stream;1"].createInstance(gPFFCI.nsIBufferedInputStream);
      bufStream.init(fstream, 8192);
      return bufStream;
    },
    
    getTargetURI: function(aProtocol, aUserName, aPassword, aHost, aPath) {
      var uri = gPFFCC["@mozilla.org/network/standard-url;1"].createInstance(gPFFCI.nsIURI);
      //uri.spec = "ftp://"+aUserName+":"+aPassword+"@"+ftpURi;
      uri.spec = aProtocol + "://" + aUserName + ":" + aPassword + "@" + aHost + "/" + aPath;
      return uri;
    },
    
    sendBinaryImage: function(theFilePath, aProtocol, aUserName, aPassword, aHost, aPath) {
        var myFile = gTempObject; //Use the picked file, not the path from the textbox.
        this.upload(this.getUploadStreamForFile(myFile), this.getTargetURI(aProtocol, aUserName, aPassword, aHost, aPath));
    },
    
    getErrorStr: function(aCode){
      if(aCode == 0) return "done";
      if(aCode < gPFF_MAGIC_NUMBER) return "notneterror";
      aCode %= gPFF_MAGIC_NUMBER;
      //LOG(this.aCode);
      if(aCode in gPFFNetErrorStrings){
        return gPFFNetErrorStrings[aCode];
      }
      return "unexpected";
    },
    
	cancelUpload: function() {
		if (gPFFChannel) {
			gPFFChannel.cancel(gPFF_MAGIC_NUMBER + 2);
		}
	},
    
    onReturn: function(aCode) {
        if (aCode == 0) {
			// success
            gUploadDialogService.uploadFTPGood();
        }
		else {
			// xxx beep, perhaps?  // failure - don't close
            var theError = this.getErrorStr(aCode);
            gUploadDialogService.onUploadError(theError, aCode);
        }
    },
    
    //Prep Binary Data
    prepBinaryToBase64Data: function(aNsiFile) {
		return btoa(this.getBinaryData(aNsiFile));
    },
    
	getBinaryData : function (aNsiFile) {
        var fileInStream = Components.classes["@mozilla.org/network/file-input-stream;1"].createInstance(Components.interfaces.nsIFileInputStream); 
        fileInStream.init(aNsiFile, 0x01, 0644, false);
        var binaryInStream = Components.classes["@mozilla.org/binaryinputstream;1"] .createInstance(Components.interfaces.nsIBinaryInputStream); 
        binaryInStream.setInputStream(fileInStream); 
        var theData = binaryInStream.readBytes( binaryInStream.available() );
		return theData;
	},

    //Do newMediaObject File Upload
    //metaWeblog.newMediaObject (blogid, username, password, struct)
    doMediaFileUpload: function(aNsiFile) {
        var theBase64Data = this.prepBinaryToBase64Data(aNsiFile);
        if ((gOpener.SCRIBEFIRE_BLOG.guid) || gOpener.SF_QUICKBLOG){
            var mimeSvc = Components.classes["@mozilla.org/mime;1"].getService(Components.interfaces.nsIMIMEService);
            var theMimeType = mimeSvc.getTypeFromFile(aNsiFile);
            var myResponse = gOpener.SCRIBEFIRE_BLOG.serviceObject.fileUpload(aNsiFile.leafName, theMimeType, theBase64Data);
            
            //Do and handle the Post Request
            var theCall = new PffXmlHttpReq(gOpener.SCRIBEFIRE_BLOG.api, "POST", myResponse, false, null, null, null);
            theCall.onResult  = function(aText, aXML){
                gUploadService.onBlogApiResponse( aText, aXML, gOpener.SCRIBEFIRE_BLOG.url );
            }
            theCall.onError  = function(aText, aXML){
                var localeString = performancingUI.getLocaleString('errorcontactingserver');
                gUploadDialogService.onUploadError(localeString,"");
            }
            theCall.prepCall(); //Set up The call (open connection, etc.)
            theCall.request.setRequestHeader("Content-Type", "text/xml");
            theCall.makeCall(); //Make the call
            theCall.request.overrideMimeType ('text/xml');
        }
    },
    
    onBlogApiResponse: function(aResponseText, aResponseXML, aBlogUrl) {
        var re = /(\<\?\xml[0-9A-Za-z\D]*\?\>)/;
        var newstr = aResponseText.replace(re, "");
        var e4xXMLObject = new XML(newstr);
        gPffTempUploadObject.push(e4xXMLObject);
		
        var ourParsedResponse = null; 
        if (e4xXMLObject.params.param.value.length() >= 1){
            ourParsedResponse = gOpener.bfXMLRPC.XMLToObject(e4xXMLObject.params.param.value.children()[0]); 
        }else if (e4xXMLObject.fault.value.length() >= 1){
            ourParsedResponse = gOpener.bfXMLRPC.XMLToObject(e4xXMLObject.fault.value.children()[0]); 
        }
        gPffTempUploadObject.push(ourParsedResponse);
        if(ourParsedResponse.faultString || !ourParsedResponse.url){
            var localeString = "";
            var localeString2 = performancingUI.getLocaleString('noImageUpload');
            var localeString3 = performancingUI.getLocaleString('noImageUpload2');
            if(ourParsedResponse.faultString){
                localeString = performancingUI.getLocaleString('requesterror', [ ourParsedResponse.faultString ]);
            }

            alert(localeString2 + "\n\n" + localeString3 + "\n\n" + localeString);

            gUploadDialogService.onUploadError(ourParsedResponse.faultString,"");
        }else if(ourParsedResponse.url){
            //Construct the URL
            var theNewURL = "";
            if( /https?:/.test(ourParsedResponse.url.toString()) ){
                theNewURL = ourParsedResponse.url;
            }else{
                if(aBlogUrl.charAt(aBlogUrl.length -1) == "/" && ourParsedResponse.url.charAt(0) == "/"){
                    theNewURL = aBlogUrl.substr(0, aBlogUrl.length -1) + ourParsedResponse.url;
                }else{
                    theNewURL = aBlogUrl + ourParsedResponse.url;
                }
            }
            gUploadDialogService.uploadBlogAPIGood(theNewURL);
        }
    }
}

// this object gets progress notifications
var gPFFStreamListener = {
  onDataAvailable: function(aChannel, aCtxt, aInStr, aSourceOffset, aCount) {},
  onStartRequest: function(aChannel, aCtxt) {},
  onStopRequest: function(aChannel, aCtxt, aErrCode) {
    gUploadService.onReturn(aErrCode);
  }
};


//DIALOG SETTINGS, ETC.

gUploadDialogService = new Object();

var gUploadDialogService = {
	get prefs() { return oPerformancingUtil.prefs; },
	
    onLoad: function() {
		setTimeout(function () { gUploadDialogService.continueOnLoad(); }, 500);
	},
	
	continueOnLoad : function () {
		if (window.arguments[1] && window.arguments[1] != '') {
			document.getElementById("upload-ftp-uri").value = decodeURIComponent(window.arguments[1]);
			var thefile = PerFormancingFileIO.fileFromPath(document.getElementById("upload-ftp-uri").value);
			gTempObject = thefile;
			gUploadDialogService.confirmUploadType();
		}
    },
    
	imagePicker : function () {
		this.onFilePick(true);
	},

    filePicker: function(){
        this.onFilePick(false); //False to filter only images
    },
    
	acceptUpload : function () {
		var imageUrl = currentImagePath;
		
		if (!imageUrl) {
			imageUrl = document.getElementById("upload-ftp-uri").value;
			
			if (!imageUrl) {
				re[0] = false;
				return true;
			}
			else {
				this.confirmUploadType();
			}
		}
		else {
			var theURL = window.arguments[1];
			var re = window.arguments[0]; 
			theURL[0] = imageUrl;
			re[0] = true;

			return true;
		}
		
		return false;
	},
	
	//CopyURl to clipboard
    copyURLToClipboard: function(aURL){
        //gContextMenu.getService('@mozilla.org/widget/clipboardhelper;1', Components.interfaces.nsIClipboardHelper).copyString(gContextMenu.linkText())
        if (currentImagePath != ""){
            try{
                var clipBoard = gPFFCC["@mozilla.org/widget/clipboardhelper;1"].getService(gPFFCI.nsIClipboardHelper);
                //clipBoard.copyString(aURL);
                clipBoard.copyString(currentImagePath);
            }catch(e){
                var localeString = performancingUI.getLocaleString('cantsaveurltoclip');
                alert(localeString);
            }
            return true;
        }
    },

	onFilePick: function(imageFilter) {
		var nsIFilePicker = Components.interfaces.nsIFilePicker;
		var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);

		if(imageFilter){
			fp.appendFilters(nsIFilePicker.filterImages);
			var localeString = performancingUI.getLocaleString('selectimagefile');
		}
		else {
			var localeString = performancingUI.getLocaleString('selectfile');
		}

		fp.init(window, localeString, nsIFilePicker.modeOpen);
		var res = fp.show();

		if (res == nsIFilePicker.returnOK){
			var thefile = fp.file;
			gTempObject = thefile;
			document.getElementById("upload-ftp-uri").value = thefile.path;
			this.confirmUploadType();
		}
	},
	
	confirmUploadType : function () {
		// Check if it should be FTP or API.
		
		var apiAvailable = gOpener.SCRIBEFIRE_BLOG.supportsUploads;
		var ftpAvailable = gOpener.SCRIBEFIRE_BLOG.ftp_username && gOpener.SCRIBEFIRE_BLOG.ftp_host;
		
		if (window.arguments[2] && oPerformancingUtil.prefs.getCharPref("lastUploadMethod") != "") {
			switch (oPerformancingUtil.prefs.getCharPref("lastUploadMethod")) {
				case "api":
					var button = 0;
				break;
				case "ftp":
					var button = 1;
				break;
			}
		}
		else if (gOpener.SCRIBEFIRE_BLOG.serviceObject) {
			if (apiAvailable && ftpAvailable) {
				// Only prompt for an upload method if they're opening it from the editor.
				var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
				                        .getService(Components.interfaces.nsIPromptService);
				var check = { value : false };
				var flags = prompts.BUTTON_POS_0 * prompts.BUTTON_TITLE_IS_STRING + prompts.BUTTON_POS_1 * prompts.BUTTON_TITLE_IS_STRING + prompts.BUTTON_POS_2 * prompts.BUTTON_TITLE_IS_STRING;
		
				var button = prompts.confirmEx(
						window, 
						performancingUI.getLocaleString("Upload Type"),
						performancingUI.getLocaleString("uploadMethodChoice"),
						flags, 
						performancingUI.getLocaleString("API"),
						performancingUI.getLocaleString("FTP"),
						performancingUI.getLocaleString("cancel"),
						null, 
						check);
			}
			else if (apiAvailable) {
				button = 0;
			}
			else if (ftpAvailable) {
				button = 1;
			}
			else {
				alert("API not available; set up FTP.");
				button = 2;
			}
		}
		else {
			var button = 1;
		}
		
		if (button == 0) {
			oPerformancingUtil.prefs.setCharPref("lastUploadMethod", "api");
			
			// API
			gUploadDialogService.onBlogApiUploadStarted();
		}
		else if (button == 1) {
			oPerformancingUtil.prefs.setCharPref("lastUploadMethod", "ftp");
			
			// FTP
			gUploadDialogService.onUploadStarted();
		}
		else if (button == 2) {
			// Cancel
		}
	},
    
    tryUpload: function() {
		var prefs = this.prefs;
		var stringBundle = document.getElementById("performancingstrings");

		var username = gOpener.SCRIBEFIRE_BLOG.ftp_username;
		var host = gOpener.SCRIBEFIRE_BLOG.ftp_host;
		var password = oPerformancingUtil.usermanagment.getPassword(username, "-ftp-" + host);
		var path = gOpener.SCRIBEFIRE_BLOG.ftp_path;
		var url_to_path = gOpener.SCRIBEFIRE_BLOG.ftp_url_to_path;
		var theProtocol = gOpener.SCRIBEFIRE_BLOG.ftp_protocol;
		
		if (host != "" && username != "" && password != "" ){
			var theFilePath = document.getElementById("upload-ftp-uri").value;

			if(theFilePath != ""){
				this.deckToggle(true);
				var theFileName = gTempObject.leafName;
				gUploadService.sendBinaryImage(theFilePath, theProtocol, username, password, host, path + theFileName);
			}
			else{
				var localeString = performancingUI.getLocaleString('selectafile');
				alert(localeString);
			}
		}
		else {
			var localeString = performancingUI.getLocaleString('setupftp');
			alert(localeString);
		}
    },
	
	invalidTokens : 0,
	
	tryMediaBlogUpload: function() {
		if (gOpener.SCRIBEFIRE_BLOG.type.indexOf("blogger") != -1){
			// Special treatment for Blogger: Upload to Picasa Web Album
			
			this.deckToggle(true);
			
			// Watch for the token.
			
			var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService).getBranch("performancing.");
			
			function doUpload(token) {
				var aNsiFile = gTempObject;
				var mimeSvc = Components.classes["@mozilla.org/mime;1"].getService(Components.interfaces.nsIMIMEService);
				var theMimeType = mimeSvc.getTypeFromFile(aNsiFile);

				const MULTI = "@mozilla.org/io/multiplex-input-stream;1";
				const FINPUT = "@mozilla.org/network/file-input-stream;1";
				const BUFFERED = "@mozilla.org/network/buffered-input-stream;1";

				const nsIMultiplexInputStream = Components.interfaces.nsIMultiplexInputStream;
				const nsIFileInputStream = Components.interfaces.nsIFileInputStream;
				const nsIBufferedInputStream = Components.interfaces.nsIBufferedInputStream;

				var buf = null;
				var fin = null;

				var fpLocal  = Components.classes['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
				fpLocal.initWithFile(aNsiFile);

				fin = Components.classes[FINPUT].createInstance(nsIFileInputStream);				
				fin.init(fpLocal, 1, 0, false); 

				buf = Components.classes[BUFFERED].createInstance(nsIBufferedInputStream);
				buf.init(fin, 9000000);

				var uploadStream = Components.classes[MULTI].createInstance(nsIMultiplexInputStream);
				uploadStream.appendStream(buf);

				var upreq = new XMLHttpRequest();
				upreq.open("POST", "http://picasaweb.google.com/data/feed/api/user/default/albumid/default", true);
				upreq.setRequestHeader("Authorization","AuthSub token="+token);
				upreq.setRequestHeader("Content-Type", theMimeType);
				upreq.setRequestHeader("Content-Length", (uploadStream.available()));
				upreq.overrideMimeType("text/xml");

				upreq.onreadystatechange = function () {
					if (upreq.readyState == 4) {
						if (upreq.status < 300) {
							gUploadDialogService.invalidTokens = 0;

							try {
								var imageUrl = upreq.responseXML.getElementsByTagName("content")[0].getAttribute("src") + "?imgmax=800";
								gUploadDialogService.uploadBlogAPIGood(imageUrl);
							} catch (e) {
								gUploadDialogService.onUploadError(performancingUI.getLocaleString("upload.error.googleError", [upreq.responseText]));
							}
						}
						else {
							if (upreq.status == 403 && upreq.responseText.match(/Token invalid/)) {
								gUploadDialogService.invalidTokens++;

								if (gUploadDialogService.invalidTokens > 1) {
									gUploadDialogService.onUploadError(performancingUI.getLocaleString("upload.error.authTokenAcquire"));
								}
								else {
									delete tokens_json[gOpener.SCRIBEFIRE_BLOG.serviceObject.username];

									prefs.setCharPref("google_tokens", JSON.stringify(tokens_json));

									prefs.setCharPref("google_token", "");
									gUploadDialogService.tryMediaBlogUpload();
								}
							}
							else if (upreq.responseText.match(/Must sign terms/i)) {
								gOpener.parent.getWebBrowser().selectedTab = gOpener.parent.getWebBrowser().addTab("http://picasaweb.google.com/");
								alert(performancingUI.getLocaleString("upload.error.picasaTerms"));
							}
							else {
								gUploadDialogService.onUploadError(performancingUI.getLocaleString("upload.error.noApi"));
								SFLOG(upreq.responseText);
							}
						}
					}
				};
				
				upreq.send(uploadStream);
			}
			
			var prefObserver = {
				observe : function (subject, topic, data) {
					if (topic == 'nsPref:changed') {
						if (data == 'google_token') {
							// When it appears, do this:
							
							var token = prefs.getCharPref("google_token");
							
							if (!token) {
								return;
							}
							
							var req = new XMLHttpRequest();
							req.open("GET", "https://www.google.com/accounts/AuthSubSessionToken", true);
							req.setRequestHeader("Authorization","AuthSub token=\""+token+"\"");
							
							req.onreadystatechange = function () {
								if (req.readyState == 4) {
									if (req.status == 200) {
										var lines = req.responseText.split("\n");
										var newTokenLine = lines[0];
										var newToken = newTokenLine.split("=")[1];
										
										var tokens_json = prefs.getCharPref("google_tokens");

										try {
											tokens_json = JSON.parse(tokens_json);
										} catch (e) {
											tokens_json = {};
										}

										tokens_json[gOpener.SCRIBEFIRE_BLOG.serviceObject.username] = newToken;
										prefs.setCharPref("google_tokens", JSON.stringify(tokens_json));
										
										doUpload(newToken);
									}
									else {
										gUploadDialogService.onUploadError(performancingUI.getLocaleString("upload.error.authTokenAcquire"));
									}
								}
							};
							
							req.send(null);
						}
					}
				}
			};
			
			prefs.QueryInterface(Components.interfaces.nsIPrefBranch2);
			prefs.addObserver("", prefObserver, false);
			
			var tokens_json = prefs.getCharPref("google_tokens");
			
			try {
				tokens_json = JSON.parse(tokens_json);
				
				if (gOpener.SCRIBEFIRE_BLOG.serviceObject.username in tokens_json) {
					doUpload(tokens_json[gOpener.SCRIBEFIRE_BLOG.serviceObject.username]);
					return;
				}
			} catch (e) {
			}
			
			gUploadDialogService.invalidTokens++;
			
			window.open("https://www.google.com/accounts/AuthSubRequest"
					+ "?scope="+encodeURIComponent('http://picasaweb.google.com/data/')
					+ "&next="+ encodeURIComponent('http://www.scribefire.com/token.php') +"&session=1", "sf-google-token", "height=400,width=600,menubar=no,toolbar=no,location=no,personalbar=no,status=no");
		}
		else {
            var theFilePath = document.getElementById("upload-ftp-uri").value;

            if(theFilePath != ""){
                this.deckToggle(true);
                gUploadService.doMediaFileUpload(gTempObject);
            }else{
                var localeString = performancingUI.getLocaleString('selectafile');
                alert(localeString);
            }
		}
    },
    
    //On Upload Start
    onUploadStarted: function() {
        var localeString = performancingUI.getLocaleString('uploading');
        document.getElementById("upload-upload-progress-text").setAttribute("value", localeString);
        gUploadService.serviceType = "ftp";
        this.tryUpload();
    },
    
    //Start Blog API upload (newMediaObject)
    onBlogApiUploadStarted: function() {
		if ("handleFileUpload" in gOpener.SCRIBEFIRE_BLOG.serviceObject) {
			gOpener.SCRIBEFIRE_BLOG.serviceObject.handleFileUpload(gTempObject);
			window.close();
		}
		else {
	        var localeString = performancingUI.getLocaleString('uploading');
	        document.getElementById("upload-upload-progress-text").setAttribute("value", localeString);
	        this.tryMediaBlogUpload();
	        gUploadService.serviceType = "blogapi";
		}
    },
    
    uploadFTPGood: function() {
        var localeString = performancingUI.getLocaleString('uploadcanceled');
        this.setFeedbackText(localeString, false);
        this.deckToggle();
        this.onFtpUploadDone();

		if (gUploadDialogService.onDialogAccept()) {
			if (!document.getElementById("ftp-upload-window")) {
				window.close();
			}
		}
    },
    
    uploadBlogAPIGood: function(aURL) {
        var localeString = performancingUI.getLocaleString('uploadcanceled');
        this.setFeedbackText(localeString, false);
        this.deckToggle();
        this.onBlogAPIUploadDone(aURL);

		if (gUploadDialogService.onDialogAccept()) {
			if (!document.getElementById("ftp-upload-window")) {
				window.close();
			}
		}
    },
    
    //Set upload status here:
    setFeedbackText: function(aText, isError) {
        var theLabel = document.getElementById("upload-ftp-upload-status");
        theLabel.value = aText;
        if(isError){
            theLabel.setAttribute("style", "color: red;");
        }else{
            theLabel.setAttribute("style", "color: blue;");
        }
    },
    
    //On FTP Upload success
    onFtpUploadDone: function() { //gUploadDialogService.uploadFTPGood();
        var url_to_path = gOpener.SCRIBEFIRE_BLOG.ftp_url_to_path;
        currentImagePath = url_to_path + gTempObject.leafName;
		try { document.getElementById("uploaded-file-url").value = url_to_path + gTempObject.leafName; document.getElementById("upload-ftp-deck").selectedIndex = 2; } catch (e) { };
		
    },
    
    onBlogAPIUploadDone: function(aURL) { //gUploadDialogService.uploadFTPGood();
        currentImagePath = aURL;
		try { document.getElementById("uploaded-file-url").value = aURL;  document.getElementById("upload-ftp-deck").selectedIndex = 2;  } catch (e) { };
		
    },
    
    onDialogAccept: function() {
		var theImageURL = currentImagePath;
		
		if (theImageURL != "") {
			var theURL = window.arguments[1];
			var re = window.arguments[0]; 
			theURL[0] = theImageURL;
			re[0] = true;
		}
			
		return true;
    },
    
    setErrorTimer: function(){
        gTheErrorTimer = window.setTimeout(function () { gUploadDialogService.deckToggle(); }, 1000);
    },
    
    cancelErrorTimer: function(){
        window.clearTimeout(gTheErrorTimer);
    },
    
    onUploadError: function(theError){
        this.setErrorTimer();
        var localeString = performancingUI.getLocaleString('uploaderror');
        var localeString2 = performancingUI.getLocaleString('theerror', [theError]);
        document.getElementById("upload-upload-progress-text").setAttribute("value", localeString);
        this.setFeedbackText(localeString2, true);
    },
    
    deckToggle : function (notError) {
        var theDeck = document.getElementById('upload-ftp-deck');

        if (!notError){
            theDeck.setAttribute('selectedIndex', 0);
        }
		else{
            theDeck.setAttribute('selectedIndex', 1);
        }
    }
};

function pffCreatePostRequest(args) {
	const BOUNDARY="---------------------------32191240128944"; 
	
	const MULTI = "@mozilla.org/io/multiplex-input-stream;1";
	const STRINGIS = "@mozilla.org/io/string-input-stream;1";
	const BUFFERED = "@mozilla.org/network/buffered-input-stream;1";
													   
	const nsIMultiplexInputStream = Components.interfaces.nsIMultiplexInputStream;
	const nsIStringInputStream = Components.interfaces.nsIStringInputStream;
	const nsIBufferedInputStream = Components.interfaces.nsIBufferedInputStream;
	
	var sheader = '';
	
	for (var i in args) {
		sheader += "--" + BOUNDARY + "\r\n";
		sheader += "Content-Disposition: form-data; name=\"" + encodeURIComponent(i) + "\"";
		
		if (typeof args[i] == "object") {
			if (args[i].type == 'file') {
				sheader += " filename=\"" + args[i].filename + "\"";
			
				if (args[i].headers.length > 0) {
					for (var q = 0; q < args[i].headers.length; q++){
						sheader += "\r\n" + args[i].headers[q];
					}
				}
			
				sheader += args[i].content;
			}
		}
		
		sheader += "\r\n";
		
		sheader += "\r\n";
		sheader += args[i];
		sheader += "\r\n";
	}
	
	sheader += "--" + BOUNDARY + "--\r\n";
	sheader = encodeToUtf8(sheader);
	var hsis = Components.classes[STRINGIS].createInstance(nsIStringInputStream);
	hsis.setData(sheader,sheader.length);

	var uploadStream = Components.classes[MULTI].createInstance(nsIMultiplexInputStream);
	uploadStream.appendStream(hsis);
	
	return { "requestBody" : uploadStream, "boundary": BOUNDARY };
	
	function encodeToUtf8(oStr) {
		var utfStr = oStr;
		var uConv = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Components.interfaces.nsIScriptableUnicodeConverter); 
		uConv.charset = "UTF-8";	 	 
		utfStr = uConv.ConvertFromUnicode (oStr);	 	 
		return utfStr;
	}
}